<template>
  <div class="as-popover"
       ref="asPopover"
       @mouseenter="enterPop"
       @mouseleave="leavePop"
       :class="['as-popover--'+placement,'as-popover--'+theme]">
    <transition name="as-fade">
      <div class="as-popover__body"
           :style="style"
           v-show="visible">
        <div class="as-popover__body_title">{{title}}</div>
        <div class="as-popover__body_content">{{content}}</div>
      </div>
    </transition>
    <div @click="clickPop"
         @mousedown="mouseDown"
         @mouseup="mouseUp">
      <slot></slot>
    </div>
  </div>
</template>

<script type="text/ecmascript-6">
export default {
  name: "AsPopover",
  props: {
    title: {
      type: String,
      default: "标题"
    },
    content: {
      type: String,
      default: "内容"
    },
    placement: {
      type: String,
      default: "top"
    },
    triggler: {
      type: String,
      default: "hover"
    },
    theme: {
      type: String,
      default: "light"
    }
  },
  data() {
    return {
      visible: false,
      timeout: null,
      style: {},
      clickEvent: e => {
        if (
          this.$refs.asPopover &&
          !this.$refs.asPopover.contains(e.target) &&
          this.triggler === "click"
        ) {
          this.visible = false;
        }
      }
    };
  },
  destroyed() {
    window.removeEventListener("click", this.clickEvent);
  },
  updated() {
    this.calcPosition();
  },
  mounted() {
    this.calcPosition();

    window.addEventListener("click", this.clickEvent);
  },
  methods: {
    calcPosition() {
      let position, length;

      let { width, height } = this.$el.getBoundingClientRect();
      switch (this.placement) {
        case "top":
          position = "bottom";
          length = height + "px";
          break;
        case "bottom":
          position = "top";
          length = height + "px";
          break;
        case "left":
          position = "right";
          length = width + "px";
          break;
        case "right":
          position = "left";
          length = width + "px";
          break;
      }

      this.style = position + ":" + length;
    },
    enterPop() {
      if (!this.triggler || this.triggler === "hover") {
        clearTimeout(this.timeout);
        this.visible = true;
      }
    },
    leavePop() {
      if (!this.triggler || this.triggler === "hover") {
        this.timeout = setTimeout(() => {
          this.visible = false;
        }, 400);
      }
    },
    clickPop() {
      if (this.triggler === "click") {
        this.visible = !this.visible;
      }
    },
    mouseDown() {
      if (this.triggler === "focus") {
        this.visible = true;
      }
    },
    mouseUp() {
      if (this.triggler === "focus") {
        this.visible = false;
      }
    }
  }
};
</script>
